import { useEffect } from "react"
import { isFunction } from "./utils"
import { removeAllPendingRequestsRecord } from "utils/request"
import usePersistFn from "./usePersistFn"

/**
 * 只在组件 unmount 时执行的 hook。
 * @param fn unmount 时执行的函数
 */
const useUnmount = (fn: any) => {
  const fnPersist = usePersistFn(fn)

  useEffect(
    () => () => {
      if (isFunction(fnPersist)) {
        fnPersist()
      }

      // 中断当前所有请求
      removeAllPendingRequestsRecord()
    },
    []
  )
}

export default useUnmount
